package cn.com.longfuinfo.wx.controller;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Duang;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.com.longfuinfo.wx.common.OrderCode;
import cn.com.longfuinfo.wx.common.SysConfig;
import cn.com.longfuinfo.wx.dao.Goods;
import cn.com.longfuinfo.wx.dao.Order;
import cn.com.longfuinfo.wx.dao.OrderPayAPIRecord;
import cn.com.longfuinfo.wx.dao.Recharge;
import cn.com.longfuinfo.wx.dao.User;
import cn.com.longfuinfo.wx.dao.UserMoney;
import cn.com.longfuinfo.wx.dao.UserValueLog;
import cn.com.longfuinfo.wx.dao.WxUser;
import cn.com.longfuinfo.wx.kit.CommonKit;
import cn.com.longfuinfo.wx.kit.DatetimeKit;
import cn.com.longfuinfo.wx.kit.DoubleKit;
import cn.com.longfuinfo.wx.kit.SMSKit;
import cn.com.longfuinfo.wx.pay.wx.kit.UtilKit;
import cn.com.longfuinfo.wx.pay.wx.response.NoticeResData;
import cn.com.longfuinfo.wx.service.GoodsService;
import cn.com.longfuinfo.wx.service.OrderService;
import cn.com.longfuinfo.wx.service.UserService;

/**
 * 各个支付平台支付结果处理回调通知处理类
 */
public class OrderPayNotifyController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(OrderPayNotifyController.class);
	OrderService orderService = Duang.duang(OrderService.class);
	UserService userService = Duang.duang(UserService.class);
    GoodsService goodservice = Duang.duang(GoodsService.class);

	/**
	 * 微信订单支付结果通知处理
	 */
	@Clear
	@Before(Tx.class)
	public void wx() {
		//获取支付平台发送的通知信息
		String returnContent = getRequestStr();
		double sppoint=0;
		double jkpoint=0;
		double jypoint=0;
		
		//如果为空，则获取失败
		if(StrKit.isBlank(returnContent)){
			renderText("<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[获取支付结果通知信息失败！]]></return_msg></xml>");
			return;
		}
		//转换为对象
		NoticeResData noticeResData = (NoticeResData)UtilKit.getObjectFromXML(returnContent, NoticeResData.class);
		if(noticeResData!=null){
			//第一步验证，“返回状态码”为“SUCCESS”，且“业务结果”为“SUCCESS”
			if(noticeResData.getReturn_code().equalsIgnoreCase("SUCCESS") && noticeResData.getResult_code().equalsIgnoreCase("SUCCESS")){
				//第二步验证，通知过来的订单号是否存在
				String orderNum = noticeResData.getOut_trade_no();
				//BE:商品订单；CZ:充值订单
				String str=orderNum.substring(0,2);
				if("BE".equals(str)){
					Order order = orderService.getOrderByOrderNum(orderNum);
					//如果订单不存在，则直接返回SUCCESS，不处理
					if(order==null){
						renderText("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[]]></return_msg></xml>");
						return;
					}
					//订单状态为已支付，则直接返回SUCCESS，不处理
					if(order.getInt("payState")==OrderCode.OrderPayState.HAD_PAY){
						renderText("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[]]></return_msg></xml>");
						return;
					}
					//记录接口记录
					new OrderPayAPIRecord()
					.set("orderNum",orderNum)
					.set("payMethod", OrderCode.OrderPayMethod.WEIXIN)
					.set("sendContent", null)
					.set("returnContent", returnContent)
					.set("flag", 1).save();
					//第三步验证，验证双方订单总金额是否一致
					double amount = 0;
					amount = DoubleKit.add(amount, order.getDouble("amount"));
					int amount_int = Double.valueOf(DoubleKit.mul(amount, 100)).intValue();
					int total_fee = Integer.valueOf(noticeResData.getTotal_fee());
					if(amount_int==total_fee){
						Date guoDate;
						//判断商品 是 实物 还是服务 获取兑换截止日期
						Goods goods=goodservice.getGoodById(order.getInt("goodsid"));
						
						Record goodSeller = goodservice.getGoodsSellerById(order.getInt("goodsid"));
						String sellerId = goodSeller.get("sellerId");//商家端分配的id
						//ok商家（SE233814893）十月商家（SE201028362）所属店铺 产后商品现金购买不赠送积分，异业购买所有商品都不赠送积分，
						if("SE233814893".equals(sellerId)||"SE201028362".equals(sellerId)){
							//产品分类：713：产前，714：产后
							if(goods.getInt("ftype")!=714){
								try {
									sppoint = SysConfig.getSppoint();
									jkpoint = SysConfig.getJkpoint();
									jypoint = SysConfig.getJypoint();
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}
						
						if(goods.getInt("times") == 1){
							guoDate=goods.getDate("endtime");
						}else{
							guoDate=goods.getDate("tuanEndtime");
						}
						//计算订单总积分
						User user= userService.findByUserid(order.getInt("userid"));
						int pointsell = order.get("payPoint");
						int pointType=order.getInt("pointType");
						int point=0;
						if(pointType==1){
							point= user.getInt("sppoint");
						}else if(pointType==2){
							point=user.getInt("jkpoint");
						}else if(pointType==3){
							point=user.getInt("jypoint");
						}
						if(pointsell>point){
							renderFailed("积分不足");
							return;
						}else{
							try {
								
								if(pointType==1){
									user.set("sppoint", user.getInt("sppoint")-pointsell+(int)DoubleKit.mul(amount, sppoint));
									user.set("jkpoint", user.getInt("jkpoint")+(int)DoubleKit.mul(amount, jkpoint));
									user.set("jypoint", user.getInt("jypoint")+(int)DoubleKit.mul(amount, jypoint));
								}else if(pointType==2){
									user.set("jkpoint", user.getInt("jkpoint")-pointsell+DoubleKit.mul(amount, jkpoint));
									user.set("sppoint", user.getInt("sppoint")+(int)DoubleKit.mul(amount, sppoint));
									user.set("jypoint", user.getInt("jypoint")+(int)DoubleKit.mul(amount, jypoint));
								}else if(pointType==3){
									user.set("jypoint", user.getInt("jypoint")-pointsell+DoubleKit.mul(amount, jypoint));
									user.set("sppoint", user.getInt("sppoint")+(int)DoubleKit.mul(amount, sppoint));
									user.set("jkpoint", user.getInt("jkpoint")+(int)DoubleKit.mul(amount, jkpoint));
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
							if(user.update()){
								String duihuanma=order.getInt("userid")+CommonKit.randomNum();
								order.set("payState", 2).set("orderState", 1)
								.set("payDate",DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
								.set("duihuanma", duihuanma);
								if(pointType==1){
									order.set("guoDate", DatetimeKit.getIntervalFormatDate(PropKit.getInt("constants.order.intervals"), "yyyy-MM-dd HH:mm:ss"));
								}else{
									order.set("guoDate",guoDate);
								}
								  if(pointType==1){ order.set("guoDate",DatetimeKit.getIntervalFormatDate(PropKit.getInt("constants.order.intervals"), "yyyy-MM-dd HH:mm:ss"));
									 
								  }else{ order.set("guoDate",guoDate);
								  
								  }
								  //服务类商品的兑换时间为后台设置的时间
								Order goodsType=orderService.getGoodsType(orderNum);
								String  types=""+goodsType.getInt("type");
								String  goodtype=""+goodsType.getInt("goodtype"); 
								  if(goodtype.equals("2") && (types.equals("1")||types.equals("3"))){
									  order.set("guoDate",guoDate);
								  }
								order.update();
								/*积分变更*/
								UserValueLog userValue=new UserValueLog();
								UserValueLog userValues=new UserValueLog();
								if(pointsell>0){
									userValue.set("userid", order.getInt("userid"))
									.set("type", 2)
									.set("describe", "购买宝贝")
									.set("storeid", order.get("storeid"))
									.set("goodsName", order.get("goodsName"))
									.set("fromOrderNum", orderNum)
									.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
									if(pointType==1){
										userValue.set("sppoint", pointsell);
									}else if(pointType==2){
										userValue.set("jkpoint", pointsell);
									}else if(pointType==3){
										userValue.set("jypoint", pointsell);
									}
									userValue.save();
								}
								try {
									
									userValues.set("userid", order.getInt("userid"))
									.set("type", 1)
									.set("describe", "购买宝贝赠送")
									.set("fromOrderNum", orderNum)
									.set("storeid", order.get("storeid"))
									.set("goodsName", order.get("goodsName"))
									.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
									.set("sppoint", (int)DoubleKit.mul(amount, sppoint))
									.set("jkpoint", (int)DoubleKit.mul(amount, jkpoint))
									.set("jypoint", (int)DoubleKit.mul(amount, jypoint))
									.save();
									orderService.log(order.getStr("orderNum"),1,"用户", "微信支付", "订单支付成功，等待系统确认");
								} catch (Exception e) {
									e.printStackTrace();
								}
								String phone=order.getStr("tel");
								Order orders=orderService.getOrderByOrderNum(orderNum);
								SMSKit.sendTplSms2(phone,orders.getTimestamp("payDate"),orderNum,orders.getStr("title"),orders.getStr("goodsName"),orders.getTimestamp("guoDate"),duihuanma);
								Record ordermessage= orderService.orderMaessage(orderNum);
								String sendNum=ordermessage.get("orderNum");
								String goodsName=ordermessage.get("goodsName");
								String name=ordermessage.get("name");
								String title=ordermessage.get("store");
								String tel=ordermessage.get("tel");
								//平台
								int type=1;
								 Record Ftype=orderService.FingFtype(orderNum);
								 if(StrKit.notNull(Ftype)){
									 int Ttype=Ftype.get("ftype");
									 if(Ttype==713){
										  type=2;
									   }else{
										  type=3;
									   }
								 }
								 List<Record> record= orderService.getBySellerPhone(type);
								 for (Record Sellerphone : record) {
									 SMSKit.sendTplStore(Sellerphone.get("phone"),title,goodsName,sendNum,name,tel);
								 }
								 //商家
								Record records= orderService.findStoreSellerId(order.get("storeid"));
								int sellerid=records.getInt("sellerid");
								List<Record> recordse= orderService.getBySellPhone(sellerid);
								for (Record Sellerphone : recordse) {
									 SMSKit.sendTplStore(Sellerphone.get("phone"),title,goodsName,sendNum,name,tel);
								 }
								//店铺
								int storeid=records.getInt("id");
								List<Record> recordst= orderService.getByStorePhone(storeid);
								for (Record Sellerphone : recordst) {
									 SMSKit.sendTplStore(Sellerphone.get("phone"),title,goodsName,sendNum,name,tel);
								 }
							}
						}
						
						renderText("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[]]></return_msg></xml>");
						return;
					}else{
						renderText("<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[订单金额校验错误]]></return_msg></xml>");
						return;
					}
				}else if("CZ".equals(str)){
					//记录接口记录
					new OrderPayAPIRecord()
					.set("orderNum",orderNum)
					.set("payMethod", OrderCode.OrderPayMethod.WEIXIN)
					.set("sendContent", null)
					.set("returnContent", returnContent)
					.set("flag", 2).save();
					Recharge rec=userService.getRecharrge(orderNum);
					if(rec==null){
						renderText("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[]]></return_msg></xml>");
						return;
					}
					User user= userService.findByUserid(rec.getInt("userid"));
					double money=user.getDouble("money");
					user.set("money", money+Double.valueOf(noticeResData.getTotal_fee())/100);
					if(user.update()){
						//充值记录
						rec.set("amount", Double.valueOf(noticeResData.getTotal_fee())/100)
						.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).update();
						/*货币变更*/
						UserMoney userMoney=new UserMoney();
						userMoney.set("userid", rec.getInt("userid"))
						.set("amount", Double.valueOf(noticeResData.getTotal_fee())/100)
						.set("type", 1)
						.set("describe", "账户充值")
						.set("orderType", 2)
						.set("fromOrderNum", orderNum)
						.set("nowAmount",money+Double.valueOf(noticeResData.getTotal_fee())/100)
						.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).save();
						renderText("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[]]></return_msg></xml>");
						return;
					}else{
						renderText("<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[充值失败]]></return_msg></xml>");
						return;
					}
				}
			}
		}
	}
	/**
	 * 从request中获取输入流
	 */
	private String getRequestStr(){
		try {
			HttpServletRequest request = this.getRequest();
			InputStream inStream = request.getInputStream();
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
				outSteam.write(buffer, 0, len);
			}
			outSteam.close();
			inStream.close();
			return new String(outSteam.toByteArray(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("接收支付结果通知内容时出错！");
		}
		return null;
	}
}
